<template>
  <div>
    <p>
      <span
        v-for="(char, index) in displayChars"
        :key="`${currentIndex}-${index}`"
        :class="char.animationClass"
        class="char"
      >
        {{ char.text }}
      </span>
    </p>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue"

// 诗词数组
const textData = [
  "折得一枝杨柳，归来插向谁家？",
  "衣带渐宽终不悔，为伊消得人憔悴。",
  "泪眼问花花不语，乱红飞过秋千去。",
  "一壶酒，一竿身，快活如侬有几人。",
  "风不定，人初静，明日落红应满径。",
  "从别後，忆相逢，几回魂梦与君同。",
  "滴不尽相思血泪抛红豆，开不完春柳春花满画楼。",
  "若问闲情都几许？一川烟草，满城风絮，梅子黄时雨。"
]

// 用于显示的字符数组，每个字符都有对应的动画类
const displayChars = ref<Array<{ text: string; animationClass: string }>>([])
const currentIndex = ref(0) // 用于更新key，确保动画重新触发

// 逐个添加文字
const addText = () => {
  const poem = textData[Math.floor(Math.random() * textData.length)]
  const chars = poem.split("")
  
  // 清空之前的内容
  displayChars.value = []
  
  // 为每个字符创建对象，初始时不显示
  chars.forEach((char, index) => {
    displayChars.value.push({
      text: char,
      animationClass: 'char-hidden'
    })
  })
  
  // 逐个显示字符
  let index = 0
  const showTimer = setInterval(() => {
    if (index >= chars.length) {
      clearInterval(showTimer)
      // 所有字符显示完毕后，等待2秒开始消失动画
      setTimeout(() => {
        delText()
      }, 2000)
      return
    }
    
    // 显示当前字符，添加入场动画
    displayChars.value[index].animationClass = 'animate__animated animate__fadeInUp'
    index++
  }, 150)
}

// 逐个删减文字
const delText = () => {
  let index = 0
  const hideTimer = setInterval(() => {
    if (index >= displayChars.value.length) {
      clearInterval(hideTimer)
      // 所有字符消失完毕后，等待1秒重新开始
      setTimeout(() => {
        currentIndex.value++ // 更新索引以重置key
        addText()
      }, 1000)
      return
    }
    
    // 为当前字符添加消失动画
    displayChars.value[index].animationClass = 'animate__animated animate__hinge'
    index++
  }, 100)
}

onMounted(() => {
  setTimeout(() => {
    addText()
  }, 1000)
})
</script>

<style scoped lang="scss">
p {
  font-size: 1.5em;
  margin-top: 15px;
  font-family: "STKaiti";
  position: relative;
  display: flex;
  align-items: center;
  text-align: center;
  
  .char {
    display: inline-block;
    
    &.char-hidden {
      opacity: 0;
      visibility: hidden;
    }
  }
  
  .line {
    padding: 0;
    margin: 0;
    height: 43px;
    animation: cursor 400ms steps(44) infinite normal;
  }
  
  @keyframes cursor {
    0% {
      color: #fff;
    }

    100% {
      color: transparent;
    }
  }
}
</style>
